//
//  BMTabView.h

#import "DWTabView.h"


@interface DWTabView()
{
    CGFloat _x;
    CGFloat _w;
}

@property (nonatomic, strong) UIImageView  *indicator;
@property (nonatomic, assign) CGFloat itemWith;

/**
 *  指示条是否贴到边上,默认为YES
 */
@property (nonatomic, assign)  BOOL autoExpandIndicator;

@end


static NSUInteger const kBaseTabTag = 12333;
static NSUInteger const kSeperatorTag = 1100;

@implementation DWTabView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize
{
    self.layer.masksToBounds = YES;
    self.layer.borderWidth = 1.0f;
    self.layer.borderColor = [UIColor clearColor].CGColor;
    self.layer.cornerRadius = 12.0f;
    
    self.itemSpacing = 0;
    self.itemWith = 70;
    self.padding = 0;
    self.autoExpandIndicator = NO;
    self.multiple = 0;
    self.normalColor = [UIColor whiteColor];
    self.selectColor = COLOR_main;
    self.itemFont = [UIFont systemFontOfSize:13];
    self.selectItemFont = [UIFont systemFontOfSize:13];
    self.backgroundColor = COLOR_main;
}

- (void)setItems:(NSArray *)items
{
    _items = items;
    self.selectedIndex = 0;
    if (_items.count < 4){
        _w = 40;
        _x = 20;
    }
    [self setNeedsLayout];
}

- (UIButton *)buttonWithTitle:(NSString *)title tag:(NSUInteger)tag frame:(CGRect)frame
{
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.tag = tag;
    button.frame = frame;
    button.titleLabel.font = self.itemFont;
    button.layer.masksToBounds = YES;
    button.layer.borderWidth = 1.0f;
    button.layer.borderColor = [UIColor clearColor].CGColor;
    button.layer.cornerRadius = 12.0f;
    [button setTitleColor:self.normalColor forState:UIControlStateNormal];
    [button setTitleColor:self.selectColor forState:UIControlStateSelected];
    [button addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:title forState:UIControlStateNormal];
    return button;
}

- (void)relayoutItemViews
{
    self.itemsButton = [NSMutableArray new];
    for (NSUInteger i = 0; i < _items.count; i++) {
        UIView* view = [self viewWithTag:kBaseTabTag + i];
        [view removeFromSuperview];
    }
    if (self.isPullOver) {
        self.itemWith = ((KScreenWidth/3)* self.multiple - self.padding * 2 - _itemSpacing * (_items.count - 1)) / _items.count;
        _w = 0;
        _x = 0;
    }else{
        self.itemWith = (CGRectGetWidth(self.bounds) - self.padding * 2 - _itemSpacing * (_items.count - 1)) / _items.count;
    }

    __block CGFloat offset = self.padding;
    if (self.isPullOver) {
        offset = 5;
    }

    [_items enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        
        NSString *title = obj;
        CGRect frame = CGRectMake(offset, 0, self.itemWith, CGRectGetHeight(self.bounds));
        offset += self.itemWith + self.itemSpacing;
        UIButton* button = [self buttonWithTitle:title tag:kBaseTabTag+idx frame:frame];
        [self.itemsButton addObject:button];
        [self addSubview:button];
    }];

    [self setSelectedIndex:_selectedIndex selectionBlock:nil];
    
    if ([self.delegate respondsToSelector:@selector(doneRelayoutItemViews)]) {
        [self.delegate doneRelayoutItemViews];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self relayoutItemViews];
}

- (void)setHideIndicators:(BOOL)hideIndicators
{
    _hideIndicators = hideIndicators;
    
    _indicator.hidden = hideIndicators;
    
    UIView* seperator = [self viewWithTag:kSeperatorTag];
    seperator.hidden = hideIndicators;
}

#pragma mark - Selection

- (void)selectAction:(UIButton *)sender
{
    UIButton* selectedItem = (UIButton *)[self viewWithTag:kBaseTabTag + _selectedIndex];
    if (selectedItem) {
        selectedItem.selected = NO;
    }
    
    sender.selected = YES;
    NSUInteger index = sender.tag - kBaseTabTag;
    self.selectedIndex = index;
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex
{
    [self setSelectedIndex:selectedIndex selectionBlock:_selection];
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex selectionBlock:(BMTabViewSelection)selectionBlock
{
    UIButton* selectedItem = (UIButton *)[self viewWithTag:kBaseTabTag + _selectedIndex];
    if (selectedItem) {
        selectedItem.selected = NO;
        selectedItem.titleLabel.font = self.itemFont;
        selectedItem.backgroundColor = COLOR_main;
    }
    
    NSUInteger oldIndex = _selectedIndex;
    NSUInteger newIndex = selectedIndex;
    
    _selectedIndex = selectedIndex;
    
    if (selectionBlock) {
        selectionBlock(newIndex, oldIndex);
    }
    
    selectedItem = (UIButton *)[self viewWithTag:kBaseTabTag + _selectedIndex];
    if (selectedItem) {
        selectedItem.selected = YES;
        selectedItem.titleLabel.font = self.selectItemFont;
        selectedItem.backgroundColor = [UIColor whiteColor];
    }
    [self updateIndicator];
}

- (void)updateIndicator
{
    UIButton* selectedItem = (UIButton *)[self viewWithTag:kBaseTabTag + _selectedIndex];
    CGRect frame = _indicator.frame;
    if (frame.size.width < 40) {
        frame.size.width = 40;
    }

    frame.origin.x = selectedItem.frame.origin.x+(selectedItem.frame.size.width - frame.size.width)/2;

    if (self.autoExpandIndicator) {
        if (_selectedIndex == 0) {
            frame.size.width += frame.origin.x;
            frame.origin.x = 0;
        }else if (_selectedIndex == _items.count - 1){
            frame.size.width += CGRectGetWidth(self.bounds) - CGRectGetMaxX(frame);
        }
    }

    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.75 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        
        self.indicator.frame = frame;
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)scrollIndicatorBetweenIndex1:(NSUInteger)index1 index2:(NSUInteger)index2 withPercent:(CGFloat)percent
{
    UIButton* button1 = (UIButton *)[self viewWithTag:kBaseTabTag + index1];
  
    CGRect frame = _indicator.frame;

    frame.size.width = 40;
    frame.origin.x = (button1.frame.size.width - frame.size.width)/2+button1.frame.origin.x;

    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.75 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        
        self.indicator.frame = frame;
        
    } completion:^(BOOL finished) {
        
    }];
}

- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}
@end
